import Cookies from 'js-cookie'
import { ActionContext } from 'vuex'
import { State, RootState } from '@vue/runtime-core'
import { Persistent } from '@/utils/cache/persistent'
import { PROJ_CFG_KEY } from '@/enums/cacheEnum'
import { ProjectConfig } from '/#/config'
import { DeepPartial } from '/#/global'
import { deepMerge } from '@/utils'


const app = {
  namespaced: true,
  // module assets
  state: () => ({
    sidebar: {
      opened: Cookies.get('sidebarStatus') ? Cookies.get('sidebarStatus')!! : true,
      withoutAnimation: false
    },
    device: 'desktop',
    size: Cookies.get('size') || 'small',
    projectConfig: Persistent.getLocal(PROJ_CFG_KEY),

  }), // module state is already nested and not affected by namespace option
  getters: {
    // isAdmin () { } // -> getters['account/isAdmin']
    getProjectConfig(state:State): ProjectConfig {
      return state.projectConfig || ({} as ProjectConfig);
    },
  },
  actions: {
    // login () { }, // -> dispatch('account/login') 提交的是 mutation，而不是直接变更状态； 可以包含任意异步操作
    toggleSideBar({ commit }: ActionContext<State, RootState>) {
      commit('TOGGLE_SIDEBAR')
    },
    closeSideBar({ commit }: ActionContext<State, RootState>, { withoutAnimation }: any) {
      commit('CLOSE_SIDEBAR', withoutAnimation)
    },
    toggleDevice({ commit }: ActionContext<State, RootState>, device: string) {
      commit('TOGGLE_DEVICE', device)
    },
    setSize({ commit }: ActionContext<State, RootState>, size: number) {
      commit('SET_SIZE', size)
    },
    setProjectConfig({ commit }: ActionContext<State, RootState>,config: DeepPartial<ProjectConfig>): void {
      commit('SET_PROJECT_CONFIG',config)
    },

  },
  mutations: {
    // login () {} // -> 使用commit('account/login')来改变数据状态
    TOGGLE_SIDEBAR: (state: State) => {
      console.log('切换收展')
      state.sidebar.opened = !state.sidebar.opened
      state.sidebar.withoutAnimation = false
      if (state.sidebar.opened) {
        Cookies.set('sidebarStatus', String(true))
      } else {
        Cookies.set('sidebarStatus', String(false))
      }
    },
    // 
    CLOSE_SIDEBAR: (state: State, withoutAnimation: boolean) => {
      Cookies.set('sidebarStatus', String(false))
      state.sidebar.opened = false
      state.sidebar.withoutAnimation = withoutAnimation
    },
    TOGGLE_DEVICE: (state: State, device: string) => {
      state.device = device
    },
    SET_SIZE: (state: State, size: number) => {
      state.size = size
      Cookies.set('size', String(size))
    },
    SET_PROJECT_CONFIG:(state: State,config: DeepPartial<ProjectConfig>)=>{
      state.projectConfig = deepMerge(state.projectConfig || {}, config);
      Persistent.setLocal(PROJ_CFG_KEY, state.projectConfig);
    }
  },

}

export default app